<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java面试,">










<meta name="description" content="本文学习《剑指Java面试-Offer直通车》第三章，主要内容为: 关系型数据库相关视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta name="keywords" content="Java面试">
<meta property="og:type" content="article">
<meta property="og:title" content="【五】剑指Java面试Offer直通车-数据库相关">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/25/java-interview-offer-5/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文学习《剑指Java面试-Offer直通车》第三章，主要内容为: 关系型数据库相关视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230113104970.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230113942946.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230121919089.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191230172635744.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200109170904063.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110055038756.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110060549061.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110062328030.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110060549061.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110064054483.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110064402739.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110064530493.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110064815111.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110142859455.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110143017423.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20200110143704874.jpg">
<meta property="og:updated_time" content="2020-01-10T07:14:40.618Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【五】剑指Java面试Offer直通车-数据库相关">
<meta name="twitter:description" content="本文学习《剑指Java面试-Offer直通车》第三章，主要内容为: 关系型数据库相关视频课程地址：https://coding.imooc.com/class/303.html项目代码地址：https://gitee.com/aiolos123/java_basic">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191230113104970.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/25/java-interview-offer-5/">





  <title>【五】剑指Java面试Offer直通车-数据库相关 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/25/java-interview-offer-5/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【五】剑指Java面试Offer直通车-数据库相关</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-25T05:59:13+08:00">
                2019-12-25
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java基础/" itemprop="url" rel="index">
                    <span itemprop="name">Java基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文学习《剑指Java面试-Offer直通车》第三章，主要内容为: 关系型数据库相关<br>视频课程地址：<a href="https://coding.imooc.com/class/303.html" target="_blank" rel="noopener">https://coding.imooc.com/class/303.html</a><br>项目代码地址：<a href="https://gitee.com/aiolos123/java_basic" target="_blank" rel="noopener">https://gitee.com/aiolos123/java_basic</a></p>
<a id="more"></a>

<h2 id="关系型数据库主要面试点"><a href="#关系型数据库主要面试点" class="headerlink" title="关系型数据库主要面试点"></a>关系型数据库主要面试点</h2><p><img src="/blog/images/20191230113104970.jpg" alt="关系型数据库主要面试点"></p>
<h2 id="数据库架构"><a href="#数据库架构" class="headerlink" title="数据库架构"></a>数据库架构</h2><ol>
<li>如何设计一个关系型数据库<blockquote>
<p>考查如何分解模块，即关系型数据库的模块划分能力</p>
</blockquote>
</li>
</ol>
<p><strong>数据库的模块(设计即模块划分)</strong></p>
<ol start="2">
<li><p>数据库的模块从大类分为2类</p>
<blockquote>
<p>存储模块： 类似于OS的文件系统，用于存储数据，将数据最终持久化存于磁盘中<br>程序实例： 组织并使用、管理数据</p>
</blockquote>
</li>
<li><p>接下来我们细分”程序实例”模块：</p>
<blockquote>
<p>存储管理模块： 统一管理文件、数据的格式，即把物理数据通过逻辑形式组织、表示出来。<br>缓存机制： 把取出的数据块缓存到内存中，加快访问性能。<br>SQL解析： 编译、解析SQL指令(也要缓存编译后的SQL)<br>日志管理： 记录操作。如binlog<br>权限划分： 数据查看权限<br>容灾机制： 灾难恢复<br>索引管理： 面试重点<br>锁管理： 面试重点</p>
</blockquote>
</li>
</ol>
<p>数据库的模块如下图：<br><img src="/blog/images/20191230113942946.jpg" alt="数据库的模块划分"></p>
<ol start="4">
<li><p>如何优化存储效能：磁盘IO是导致程序执行的瓶颈，所以要尽量减少IO，所以出现了一次性读取多行的块、页的存储方式。</p>
</li>
<li><p>如何设计一个关系型数据库(即数据库的典型架构)</p>
<blockquote>
<p>答案： 首先将数据库划分为俩个部分：存储部分(该部分类似一个文件系统，用于将数据持久化到存储设备中)和程序实例部分(对存储进行逻辑上的管理)。 程序实例部分包括：存储管理模块(将数据的逻辑关系转换为物理存储关系的模块)、缓存机制(优化执行效率的模块)、SQL解析(解析SQL语句的模块)、日志管理(记录操作日志的模块)、权限划分(进行多用户管理的模块)、容灾机制(灾难恢复模块)、索引管理(优化数据查询效率的模块)、锁管理(支持数据库并发操作的模块)</p>
</blockquote>
</li>
</ol>
<h2 id="优化你的索引"><a href="#优化你的索引" class="headerlink" title="优化你的索引"></a>优化你的索引</h2><ol>
<li>为什么要使用索引————使用索引可以避免全表扫描，提高查询效率</li>
</ol>
<p>查询数据的方式</p>
<blockquote>
<p>全表扫描： 将整张表数据全部或分批加载到内存中，通过逐个块轮询查找目标数据。适用于只有几十行数据的小表。<br>使用索引： 类似字典，快速提升查询效率。</p>
</blockquote>
<ol start="2">
<li><p>什么样的信息能成为索引</p>
<blockquote>
<p>主键、唯一键、普通键等</p>
</blockquote>
</li>
<li><p>索引的数据结构————主流索引是B+树，其中MySQL不支持BitMap索引，MySQL的MyISAM和InnoDB引擎不显式支持Hash索引</p>
<blockquote>
<p>能让查询变得高效的数据结构：<br>生成索引——建立二叉查找树进行二分查找<br>生成索引——建立B-Tree结构进行查找<br>生成索引——建立B+ -Tree结构进行查找(MySql的主要方式)<br>生成索引——建立Hash结构进行查找</p>
</blockquote>
</li>
<li><p>优化你的索引</p>
<blockquote>
<p>主流的数据库索引是B+树</p>
</blockquote>
</li>
</ol>
<table>
<thead>
<tr>
<th>优化索引的方式</th>
<th>二叉查找树</th>
<th>B树</th>
<th>B+树</th>
<th>Hash索引</th>
<th>BitMap索引</th>
</tr>
</thead>
<tbody><tr>
<td>定义</td>
<td>每个节点最多有俩个子树的树结构。并且有如下特点：</td>
<td>每个节点最多有M个子树的树结构，就是M阶B树。并且有如下特点：</td>
<td>B+树是B树的变体，其定义基本与B树相同，除了：</td>
<td></td>
<td></td>
</tr>
<tr>
<td>特点</td>
<td>对任意一个节点来说，其左子树的任意节点值都小于该节点的值，其右子树的任意节点值都大于该节点的值</td>
<td>一、根节点至少包括两个孩子;树中每个节点最多含有M个孩子(M &gt;= 2);除根节点和叶节点外，其他每个节点至少有ceil(m/2)个孩子；所有叶子节点都位于同一层，即叶子节点的高度是一样的；二、假设每个非终端节点中包含有n个关键字信息，则必须满足如下图的要求</td>
<td>一、非叶子节点的子树指针与关键字个数相同；二、非叶子节点的子树指针P[i],指向关键字[K[i],K[i+1])的子树；三、非叶子节点仅用来索引，数据都保存在叶子节点中；四、所有叶子节点均有一个链指针指向下一个叶子节点，便于进行范围查询</td>
<td></td>
<td></td>
</tr>
<tr>
<td>优点</td>
<td>适用于二分查找，查询时间复杂度O(logn)</td>
<td>查询效率与二叉查找树一样，也是O(logn)；较二叉查找树的优点：树矮了很多，</td>
<td><strong>B+树更适合用来做存储索引</strong></td>
<td>理论上，查询效率高于B+树</td>
<td></td>
</tr>
<tr>
<td>缺点</td>
<td>由于存储索引的二叉查找树存在于磁盘中，随着树的深度增加，需要频繁进行磁盘IO，检索性能比全表扫描都慢</td>
<td></td>
<td></td>
<td>仅仅能满足’=’、’IN’查询，不能用于范围查询；无法被用来避免数据的排序操作；不能利用部分索引键查询；不能避免表扫描；遇到大量Hash值相等的情况后性能并不一定比B+树索引高——查询性能不稳定</td>
<td>只适用于字段的值为固定的几个值的情况；不适用于高并发场景(因为锁粒度很大)；目前只有少量数据库支持该索引(如Oracle)</td>
</tr>
<tr>
<td>图示</td>
<td><img src="/blog/images/20191230121919089.jpg" alt="二叉查找树"></td>
<td><img src="/blog/images/20191230172635744.jpg" alt="B树"></td>
<td><img src="/blog/images/20200109170904063.jpg" alt="B+树"></td>
<td><img src="/blog/images/20200110055038756.jpg" alt="Hash索引"></td>
<td></td>
</tr>
<tr>
<td>如何优化</td>
<td>让树的每个节点多存储一些子节点，即B树</td>
<td>让树的每个叶子节点多存储数据，即B+树</td>
<td></td>
<td>Hash索引从根本上不支持范围查询，查询效率也不稳定，无法优化，所以Hash索引不可以作为主流索引</td>
<td></td>
</tr>
</tbody></table>
<blockquote>
<p>B+树更适合用来做数据库存储索引的原因：</p>
<ol>
<li>B+树的磁盘读写代价更低(因为所有数据都在叶子节点，便于统一存放到磁盘的某一块中，统一读写)</li>
<li>B+树的查询效率更加稳定(所有关键字的查询长度几乎都相同，都是从根到叶子，都是O(logn))</li>
<li>B+树更有利于对数据库的扫描(利用特点四进行范围查询)</li>
</ol>
</blockquote>
<h2 id="密集索引和稀疏索引的区别"><a href="#密集索引和稀疏索引的区别" class="headerlink" title="密集索引和稀疏索引的区别"></a>密集索引和稀疏索引的区别</h2><table>
<thead>
<tr>
<th>区别</th>
<th>密集索引</th>
<th>稀疏索引</th>
</tr>
</thead>
<tbody><tr>
<td></td>
<td>密集索引文件中的每个搜索码值都对应一个索引值</td>
<td>稀疏索引文件只为索引码的某些值建立索引项</td>
</tr>
<tr>
<td></td>
<td>密集索引的叶子节点不仅保存键值，还保存了同一行记录的其他列信息</td>
<td>稀疏索引的叶子节点只保存了键信息和该行数据的地址</td>
</tr>
<tr>
<td></td>
<td>密集索引决定了文件的物理排序顺序，所以一个表只能有一个密集索引</td>
<td></td>
</tr>
<tr>
<td>密集索引与稀疏索引图示</td>
<td><img src="/blog/images/20200110060549061.jpg" alt="密集索引与稀疏索引图示"></td>
<td></td>
</tr>
</tbody></table>
<p>MySQL中的两种主要存储引擎的区别</p>
<table>
<thead>
<tr>
<th>区别</th>
<th>MyISAM</th>
<th>InnoDB</th>
</tr>
</thead>
<tbody><tr>
<td>区别</td>
<td>索引都是稀疏索引</td>
<td>有且仅有一个密集索引</td>
</tr>
<tr>
<td>选取索引的规则</td>
<td></td>
<td>若一个主键被定义，则该主键作为密集索引；若没有主键被定义，则该表的第一个唯一非空索引作为密集索引；若不满足以上条件，InnoDB内部会生成一个隐藏主键(作为密集索引)；</td>
</tr>
<tr>
<td>存储文件不同</td>
<td>索引与数据分别存储在不同文件中</td>
<td>索引与数据存储在同一个文件中</td>
</tr>
<tr>
<td>图示</td>
<td><img src="/blog/images/20200110062328030.jpg" alt="InnoDB为什么一定要有主键索引呢"></td>
<td></td>
</tr>
</tbody></table>
<p>InnoDB为什么一定要有主键索引呢？</p>
<blockquote>
<p>因为非主键索引(即稀疏索引)的叶子节点只保存了该行的主键值，不保存该行数据的地址，它包含两次查找，如下图所示：</p>
</blockquote>
<p><img src="/blog/images/20200110060549061.jpg" alt="InnoDB为什么一定要有主键索引呢"></p>
<h2 id="如何定位并优化慢查询SQL"><a href="#如何定位并优化慢查询SQL" class="headerlink" title="如何定位并优化慢查询SQL"></a>如何定位并优化慢查询SQL</h2><blockquote>
<p>答案：根据慢日志定位慢查询SQL；使用explain等工具分析SQL；修改sql或尽量让sql走索引</p>
</blockquote>
<ol>
<li>根据慢日志定位慢查询SQL<blockquote>
<p>慢日志: 记录执行的比较慢的SQL的日志</p>
</blockquote>
</li>
</ol>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 查询慢日志的配置信息</span></span><br><span class="line"><span class="keyword">show</span> <span class="keyword">variables</span> <span class="keyword">like</span> <span class="string">'%quer%'</span></span><br><span class="line"><span class="comment"># 设置慢日志的配置信息</span></span><br><span class="line"><span class="keyword">set</span> <span class="keyword">global</span> slow_query_log = <span class="keyword">on</span>;</span><br><span class="line"><span class="keyword">set</span> <span class="keyword">global</span> long_query_time = <span class="number">1</span>;</span><br><span class="line"><span class="comment"># 查看本次会话执行了慢查询的次数</span></span><br><span class="line"><span class="keyword">show</span> <span class="keyword">status</span> <span class="keyword">like</span> <span class="string">'%slow_queries%'</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20200110064054483.jpg" alt="查询并修改慢日志的配置信息"></p>
<p>打开慢日志<br><img src="/blog/images/20200110064402739.jpg" alt="打开慢日志"><br><img src="/blog/images/20200110064530493.jpg" alt="打开慢日志"></p>
<ol start="2">
<li>使用explain等工具分析SQL<blockquote>
<p>explain是分析SQL的非常有用的工具</p>
</blockquote>
</li>
</ol>
<p>关于explain各字段详解请见：《图解：实战EXPLAIN》 <a href="https://blog.csdn.net/zzti_erlie/article/details/80534733" target="_blank" rel="noopener">https://blog.csdn.net/zzti_erlie/article/details/80534733</a></p>
<p>explain的用法如下：<br><img src="/blog/images/20200110064815111.jpg" alt="explain的用法"></p>
<p>explain的关键字段:</p>
<table>
<thead>
<tr>
<th>explain的关键字段</th>
<th>type</th>
<th>extra</th>
</tr>
</thead>
<tbody><tr>
<td>需要进行优化的场景</td>
<td>MySQL找到需要的数据行方式，性能排序如下图。如果出现了index或all表示本次查询使用了全表扫描，需要进行优化</td>
<td>如果出现了Using filesort或者Using temporary，则需要进行优化</td>
</tr>
<tr>
<td>图示</td>
<td><img src="/blog/images/20200110142859455.jpg" alt="需要进行优化的type"></td>
<td><img src="/blog/images/20200110143017423.jpg" alt="需要进行优化extra"></td>
</tr>
</tbody></table>
<ol start="3">
<li>优化SQL——修改sql或尽量让sql走索引(添加索引)<br><img src="/blog/images/20200110143704874.jpg" alt="优化SQL"></li>
</ol>
<h2 id="联合索引的最左匹配原则的成因"><a href="#联合索引的最左匹配原则的成因" class="headerlink" title="联合索引的最左匹配原则的成因"></a>联合索引的最左匹配原则的成因</h2><blockquote>
<p>联合索引：由多列组成的索引</p>
</blockquote>
<ol>
<li><p>最左匹配原则: 非常重要的原则，<strong>mysql会一直向右匹配知道遇到范围查询(&gt;,&lt;,between,like)就停止查询</strong>。比如<br>a=3 and b=4 and c&gt;5 and d=6 如果创建(a,b,c,d)顺序的索引，d是用不到索引的。如果创建(a,b,d,c)的索引则都可以用的，a,b,d的顺序可以任意调整。</p>
</li>
<li><p>=和in可以乱序，比如a=1 and b=2 and c=3建立(a,b,c)索引可以任意顺序，mysql的查询优化器会帮优化成索引可以识别的形式。</p>
</li>
<li><p>联合索引的最左匹配原则的成因</p>
<blockquote>
<p>MySQL创建联合索引的规则是：首先对联合索引中的第一个字段的数据排序，然后在此基础上，再对第二个字段的数据排序（类似于Order By 字段1，字段2）。所以使用字段2进行条件判断是用不到索引的。这就是联合索引的最左匹配原则的成因</p>
</blockquote>
</li>
</ol>
<h2 id="索引是建立得越多越好吗"><a href="#索引是建立得越多越好吗" class="headerlink" title="索引是建立得越多越好吗"></a>索引是建立得越多越好吗</h2><blockquote>
<p>不是。 </p>
</blockquote>
<ol>
<li>数据量小的表不需要建立索引，建立会增加额外的索引开销。</li>
<li>数据变更需要维护索引，因此更多的索引意味着更多的维护成本。</li>
<li>更多的索引意味着需要更多的空间</li>
</ol>
<p>3-10</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Java面试/" rel="tag"># Java面试</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/24/hadoop3.0-step-by-step-3/" rel="next" title="【三】快速入门Hadoop3.0大数据处理——Hadoop三大组件详解">
                <i class="fa fa-chevron-left"></i> 【三】快速入门Hadoop3.0大数据处理——Hadoop三大组件详解
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/26/hadoop3.0-step-by-step-4/" rel="prev" title="【四】快速入门Hadoop3.0大数据处理——直播平台开播数据统计分析实际案例">
                【四】快速入门Hadoop3.0大数据处理——直播平台开播数据统计分析实际案例 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#关系型数据库主要面试点"><span class="nav-number">1.</span> <span class="nav-text">关系型数据库主要面试点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据库架构"><span class="nav-number">2.</span> <span class="nav-text">数据库架构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#优化你的索引"><span class="nav-number">3.</span> <span class="nav-text">优化你的索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#密集索引和稀疏索引的区别"><span class="nav-number">4.</span> <span class="nav-text">密集索引和稀疏索引的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何定位并优化慢查询SQL"><span class="nav-number">5.</span> <span class="nav-text">如何定位并优化慢查询SQL</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#联合索引的最左匹配原则的成因"><span class="nav-number">6.</span> <span class="nav-text">联合索引的最左匹配原则的成因</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#索引是建立得越多越好吗"><span class="nav-number">7.</span> <span class="nav-text">索引是建立得越多越好吗</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
